from django.core.mail import send_mail
from rest_framework import serializers
from django_redis import get_redis_connection

from users.models import User
from django.conf import settings

class UserRegisterSerializer(serializers.ModelSerializer):
    password2 = serializers.CharField(min_length=8,max_length=20,label="重新第二遍输入的密码",write_only=True)
    sms_code = serializers.CharField(min_length=6,max_length=6,label="短信验证码",write_only=True)
    allow = serializers.CharField(label="是否同意协议",write_only=True)
    token = serializers.CharField(label="jwt的token",read_only=True)

    class Meta:
        model = User
        fields = ["username","password","mobile","password2","sms_code","allow","id","token"]
        read_only_fields = ("id",)

        extra_kwargs = {
            "password":{
                "min_length":8,
                "max_length":20,
                "write_only":True
            }
        }


    #多字段校验
    def validate(self, attrs):
        # 获取数据
        password = attrs["password"]
        password2 = attrs["password2"]

        # 校验密码是否相同
        if password != password2:
            raise serializers.ValidationError("两次输入的密码不相同")

        # 返回响应
        return attrs

        pass

    #多字段校验
    def validate(self, attrs):
        # 获取数据
        mobile = attrs["mobile"]
        sms_code = attrs["sms_code"]

        # 校验短信验证码是否一致
        redis_conn = get_redis_connection("code")
        redis_sms_code = redis_conn.get("sms_code_%s"%mobile)
        if not redis_sms_code:
            raise serializers.ValidationError("短信验证码过期")
        if sms_code != redis_sms_code.decode():
            raise serializers.ValidationError("短信验证码错误")

        # 返回响应
        return attrs
        pass

    #单字段校验
    def validated_allow(self,value):
        # 校验是否同意条款
        if value != "true":
            raise serializers.ValidationError("必须同意条款")
        return value
        pass

    #重新create方法
    def create(self, validated_data):
        #准备要写入数据库的数据
        del validated_data["password2"]
        del validated_data["sms_code"]
        del validated_data["allow"]

        #创建数据库对象
        user = super(UserRegisterSerializer, self).create(validated_data)

        #创建完对象之后在调用方法给密码加密
        user.set_password(validated_data["password"])
        user.save()

        #注册的时候给用户设置jwt的token
        from rest_framework_jwt.settings import api_settings
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token

        #返回数据
        return user
        pass
    pass

# 登陆根本就没有使用序列化器
# class UserLoginSerilizer(serializers.Serializer):
#     username = serializers.CharField(min_length=5,max_length=20,label="用户名")
#     password = serializers.CharField(min_length=8,max_length=20,label="密码")
#
#     def validate(self, attrs):
#         #获取数据
#         username = attrs["username"]
#         password = attrs["password"]
#
#         #校验数据
#         user = User.objects.get(username=username)
#         if not user:
#             raise serializers.ValidationError("用户不存在")
#
#         if not user.check_password(password):
#             raise serializers.ValidationError("密码不正确")
#
#         return attrs

class UserInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ["id","username","mobile","email","email_active"]

    pass


class SendEmailSerializer(serializers.Serializer):
    email = serializers.EmailField(label="邮箱")
    def update(self, instance, validated_data):
        # 更新数据
        email = validated_data["email"]
        instance.email = email
        instance.save()

        # 生成一个私密连接
        verify_url = instance.generate_verify_url()

        # 发送邮件
        send_mail(subject="健康验证", message=verify_url,
                  from_email=settings.EMAIL_FROM,
                  recipient_list=[email])

        # 返回响应
        return validated_data
        pass
    pass